﻿using System;
using System.Web;

namespace _5E.Utils.WebHelper
{
    public class AjaxHandler : IHttpAsyncHandler
    {
        private static AjaxManager s_Manager = null;
        public static AjaxManager Manager { set { s_Manager = value; } }

        public bool IsReusable { get { return true; } }

        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var asyncResult = new AsyncResult(cb, context.Response);
            try
            {
                var result = s_Manager.GetResult(context);
                asyncResult.SetCompleted(result);
            }
            catch (Exception ex)
            {
                asyncResult.SetCompleted(ex: ex);
            }
            return asyncResult;
        }

        public void EndProcessRequest(IAsyncResult result)
        {
            AsyncResult asyncResult = result as AsyncResult;
            if (!string.IsNullOrEmpty(asyncResult.Result))
            {
                HttpResponse response = asyncResult.AsyncState as HttpResponse;
                response.Write(asyncResult.Result);
                response.End();
            }
        }

        public void ProcessRequest(HttpContext context)
        { }
    }
}
